package com.maxwell.impl;

import com.maxwell.entity.Order;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * User:Maxwell
 * Date:2015/2/17
 * Time:10:04
 */
@Component
public class SimpleFreemarkerTemplate {

    private static final Logger LOGGER = LoggerFactory.getLogger(SimpleFreemarkerTemplate.class);

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfig;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${mail.user.name}")
    private String fromMail;

    public String getMailText(Map<String, Object> beans, String templateName) {
        String html = null;
        try {
            Template template = freeMarkerConfig.getConfiguration().getTemplate(templateName);
            html = FreeMarkerTemplateUtils.processTemplateIntoString(template, beans);
        } catch (IOException e) {
            LOGGER.error("simple freemarker exception happened:{}",e.getMessage());
        } catch (TemplateException e) {
            LOGGER.error("simple freemarker exception happened:{}",e.getMessage());
        }
        return html;
    }

    public void sendTemplateEmail(Order order) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setSubject(order.getSubject());
            helper.setFrom(fromMail);
            helper.setTo(order.getUserEmail());

            Map<String, Object> params = new HashMap<String, Object>();
            params.put("order",order);
            String html = getMailText(params, "hello.ftl");
            helper.setText(html,true);
        } catch (MessagingException e) {
            LOGGER.error("simple freemarker exception happened:{}",e.getMessage());
        }
        javaMailSender.send(mimeMessage);
    }

}
